package section4_8;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by Hyman on 2017/6/8.
 *
 * 在执行器中周期性执行任务
 */
public class Main {

    public static void main(String[] args) {

        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        System.out.printf("Main: Starting at: %s\n", new Date());

        // 创建一个执行任务，并且将它放入执行器中，初始延迟是1秒，周期是2秒
        Task task = new Task("Task");
        ScheduledFuture<?> result = executorService.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);

        for(int i=0; i<10; i++) {
            //getDelay()方法返回任务到下一次执行时所要等待的剩余时间
            System.out.printf("Main: Delay: %d\n", result.getDelay(TimeUnit.MILLISECONDS));

            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.shutdown();

        // 验证在执行器关闭后，周期性任务不会执行
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出完成信息
        System.out.printf("Main: Finished at: %s\n", new Date());

    }

}
